package com.bianguo.android.bprinter.view.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattServerCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;

import com.bianguo.android.baselibrary.adapter.BaseRecyclerAdapter;
import com.bianguo.android.baselibrary.utils.Contacts;
import com.bianguo.android.baselibrary.utils.MLog;
import com.bianguo.android.baselibrary.utils.PermissionHelper;
import com.bianguo.android.baselibrary.view.BaseActivity;
import com.bianguo.android.bprinter.AppApplication;
import com.bianguo.android.bprinter.R;
import com.bianguo.android.bprinter.adapter.MainAdapter;
import com.bianguo.android.bprinter.annotations.PermissionCheck;
import com.bianguo.android.bprinter.runnable.BluetoothRunnable;
import com.bianguo.android.bprinter.utils.BitmapUtil;
import com.bianguo.android.bprinter.utils.BluetoothHelper;
import com.bianguo.android.bprinter.view.widget.RecycleViewDivider;
import com.bianguo.android.ioclibrary.annotations.BindView;
import com.bianguo.android.ioclibrary.annotations.OnClick;
import com.bianguo.android.opencv.utils.BitmapHelper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends BaseActivity implements BaseRecyclerAdapter.OnClickItemListener {

    @BindView(R.id.main_recycler)
    RecyclerView mRecycler;
    @BindView(R.id.printer_content)
    EditText contentEt;
    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.test_iv)
    ImageView testIv;
    @BindView(R.id.test_iv2)
    ImageView testIv2;

    private long exitTime, printTime;
    private LinearLayoutManager layoutManager;
    private MainAdapter adapter;
    private ArrayList<BluetoothDevice> devices;
    private BluetoothHelper bluetoothHelper;
    private BluetoothRunnable bluetoothRunnable;
    private ExecutorService executorService;

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        layoutManager = new LinearLayoutManager(mContext);
        mRecycler.setLayoutManager(layoutManager);
        mRecycler.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL));
        devices = new ArrayList<>();
        adapter = new MainAdapter(mContext, devices);
        adapter.setOnClickItemListener(this);
        mRecycler.setAdapter(adapter);
        IntentFilter bluetoothFilter = new IntentFilter();
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        bluetoothFilter.addAction(BluetoothDevice.ACTION_FOUND);
        bluetoothFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(bluetoothReceiver, bluetoothFilter);
        bluetoothHelper = BluetoothHelper.getInstance(mContext);
        ArrayList<BluetoothDevice> devices = bluetoothHelper.getDevices();
        if (devices != null) {
            this.devices.addAll(devices);
        }
        bluetoothRunnable = new BluetoothRunnable(bluetoothHelper.getAdapter());
        executorService = Executors.newSingleThreadExecutor();

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });
//        mWebView.loadUrl("http://www.bianguo.com.cn/index.php?g=&m=index&a=lists&type_id=4&tid=13");

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test_cat);
//        testIv.setImageBitmap(bitmap);
//        Bitmap bitmap1 = BitmapHelper.getInstance().scaleBitmap(bitmap, (float) 384 / bitmap.getWidth());
//        testIv2.setImageBitmap(bitmap1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
        if (bluetoothRunnable != null) {
            bluetoothRunnable.cancel();
            bluetoothRunnable = null;
        }
        if (executorService != null) {
            executorService.shutdown();
            executorService = null;
        }
    }

    @OnClick({R.id.open_bluetooth_btn, R.id.screen_btn, R.id.send_btn, R.id.dooding_btn})
    public void onClickBk(View view) {
        switch (view.getId()) {
            //打开蓝牙
            case R.id.open_bluetooth_btn:
//                openBluetooth();
                startActivity(new Intent(mContext, PaperActivity.class));
                break;
            //扫描蓝牙
            case R.id.screen_btn:
//                bluetoothHelper.searchDevices();
                startActivity(new Intent(mContext, WPrintActivity.class));
                break;
            //发送数据
            case R.id.send_btn:
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - printTime < 2000) {
                    return;
                }
                printTime = currentTimeMillis;
                if (bluetoothRunnable.getSocket() == null) {
                    showToast("请选择连接打印机");
                    return;
                }
                if (!bluetoothRunnable.getSocket().isConnected()) {
                    showToast("设备未连接");
                    return;
                }
                String content = contentEt.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    content = "HelloBluetoothPrinter";
                }
//                bluetoothRunnable.sendData(content);
                Bitmap bitmap = BitmapUtil.compressPic(BitmapUtil.webView2Bitmap(mWebView));
                bluetoothRunnable.printImg(bitmap);
                break;
            case R.id.dooding_btn:
                jumpDooding();
                break;
        }
    }

    @PermissionCheck(permissions = {Manifest.permission.ACCESS_COARSE_LOCATION}, requestCode = PermissionHelper.PERMISSION_BLUETOOTH)
    private void openBluetooth() {
        bluetoothHelper.open(this);
    }

    @PermissionCheck(permissions = {Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode = PermissionHelper.PERMISSION_READ)
    public void jumpDooding() {
        startActivity(new Intent(mContext, DoodingActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Contacts.START_ACTIVITY_RESULT_BLUETOOTH == requestCode) {
            //打开蓝牙
            if (RESULT_OK == resultCode) {
                //蓝牙打开成功
                //搜索蓝牙设备，结果由广播接收器接收（bluetoothReceiver）
                bluetoothHelper.searchDevices();
            }
        }
    }

    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //搜索到附近可用设备
                //获取查找到的蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (BluetoothDevice.BOND_BONDED == device.getBondState()) {
                    //已匹配
                } else {
                    //未匹配
                    devices.add(device);
                    adapter.notifyItemInserted(devices.size() - 1);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //搜索完成
                bluetoothHelper.stopSearch();
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                //连接状态的改变
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int bondState = device.getBondState();
                //蓝牙关闭 : int STATE_OFF , 值为10, 蓝牙模块处于关闭状态;
                //蓝牙打开中 : int STATE_TURNING_ON , 值为11, 蓝牙模块正在打开;
                //蓝牙开启 : int STATE_ON , 值为12, 蓝牙模块处于开启状态;
                //蓝牙开启中 : int STATE_TURNING_OFF , 值为13, 蓝牙模块正在关闭;
                MLog.mLog(device.getName() + ", " + device.getAddress() + ", " + bondState);
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - exitTime > 2000) {
                showToast("再按一次退出应用");
                exitTime = currentTimeMillis;
            } else {
                AppApplication.killAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClickItem(BaseRecyclerAdapter adapter, View view, int position, int tag) {
        switch (view.getId()) {
            case R.id.item_main_content:
                BluetoothDevice bluetoothDevice = devices.get(position);
                MLog.mLog("state = " + bluetoothDevice.getBondState());
                bluetoothRunnable.upSocket(bluetoothDevice);
                executorService.execute(bluetoothRunnable);
                break;
        }
    }
}
